<?php

namespace App\Http\Controllers\Api;

use App\Dengje\Utils\Settings;
use App\Dengje\Utils\Utils;
use App\Dengje\WeixinPay\WeixinPay;
use App\Models\WxOrder;
use App\Models\WxUser;
use Illuminate\Http\Request;


class OrderController extends BaseController
{
    /**
     * 统一下单地址
     * @param Request $request
     * @param $type 类型：1:会员 类型：2:打赏
     * @return \Illuminate\Http\JsonResponse
     */
    public function order(Request $request)
    {
        $uid = $request->uid;
        $type = $request->type;
        $parame = $request->parame;

        $orderSn = (new Utils())->getSn(1);
        $openid = WxUser::where('id', $uid)->value('weixin_openid');
        $appid = Settings::get('app_id');
        $mch_id = Settings::get('mch_id');
        $key = Settings::get('mch_secret');
        $out_trade_no = $orderSn;

        // 开会员
        if ($type == 1) {

            $body = '开通会员';
            $total_fee = Settings::get('members_price');

            // 创建订单
            $this->createOrder($uid,1,$body,$total_fee,$total_fee,$orderSn);
        }

        // 打赏
        if ($type == 2) {

            $body = '打赏';
            $total_fee = $parame['rewardPrice'];
            $parame = serialize($parame);
            // 创建订单
            $this->createOrder($uid,2,$body,$total_fee,$total_fee,$orderSn,$parame);

        }



        // 发起支付
        $payObject = new WeixinPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee);
        return $this->success($payObject->pay());
    }

    /**
     * 创建订单
     */
    public function createOrder($user_id,$order_type,$order_information,$order_price,$order_pay_price,$order_number,$parame='')
    {
        $orderModel = new WxOrder();
        $orderModel->user_id = $user_id;
        $orderModel->order_type = $order_type;
        $orderModel->order_information = $order_information;
        $orderModel->order_price = $order_price;
        $orderModel->order_pay_price = $order_pay_price;
        $orderModel->order_number = $order_number;
        $orderModel->parame = $parame;
        $orderModel->save();
    }

    /**
     * 查询轻航大会员售价
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMembersPrice(Request $request)
    {

        return $this->success(Settings::get('members_price'));
    }

}
